package com.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//编写相关Filter类实现Filter接口
public class AdminFilter implements Filter {
    public AdminFilter() {
        System.out.println("1、Filter构造器方法AdminFilter()");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("2、Filter的nit(FilterConfig filterConfig)初始化方法");
        //1、获取 Filter 的名称 filter-name 的内容(web.xml中配置的别名标签)
        System.out.println("获取filter-name的值是："+filterConfig.getFilterName());
        //2、获取在 Filter 中配置的 init-param 初始化参数
        System.out.println("初始化参数username的值是："+filterConfig.getInitParameter("username"));
        System.out.println("初始化参数url的值是："+filterConfig.getInitParameter("url"));
        //3、获取 ServletContext 对象
        System.out.println(filterConfig.getServletContext());

    }

    //doFilter方法，专门用于拦截请求，过滤响应（这里主要做拦截请求，即可以做权限检查）
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("3、Filter的doFilter()过滤方法");

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;//强制类型转换
        //获取Session中的user值
        HttpSession session = httpServletRequest.getSession();
        Object user = session.getAttribute("user");
        if (user==null){
            //如果user==null，说明还没有登录
            servletRequest.getRequestDispatcher("login.jsp").forward(servletRequest,servletResponse);
            return;//一般在请求转发后，就不允许执行后面的任何代码
        }else{
            //让程序继续往下访问用户的目标资源
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {
        System.out.println("4、Filter的destroy()销毁方法");

    }
}
